package com.spark.rectify

import android.content.DialogInterface
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.v4.app.DialogFragment
import android.support.v7.widget.GridLayoutManager
import android.view.*
import com.blankj.utilcode.util.KeyboardUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.spark.colliery.common.ext.gone
import com.spark.colliery.common.ext.watchWithClear
import com.spark.common.ext.append
import com.spark.common.ext.sdf
import com.spark.common.ext.string
import com.spark.common.ext.windowOpacity
import com.spark.common.helper.DatePickerDiaFragment
import com.spark.common.helper.SpacesItemDecoration
import kotlinx.android.synthetic.main.frag_dial_rectify_manage.*

/**
 * 隐患列表侧边栏 选择
 */
class DFRectManage : DialogFragment() {
    private val categoryList = ArrayList<String>()
    private var filterListener: FilterListener? = null
    private val tagList = ArrayList<String>()
    private var selectCategory: String = ""
    private var selectTag: String = ""

    companion object {
        fun newInstance(): DFRectManage {
            return DFRectManage()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFragmentAnimStyle)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.frag_dial_rectify_manage, null)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        dialog.window.setWindowAnimations(R.style.DialogFragmentAnimStyle)
        initLayout()
        initView()
    }

    override fun onResume() {
        super.onResume()
        activity?.windowOpacity(0.6F)
    }

    private fun initView() {
        /**
         * 分类
         */
        categoryList.add("日常办公")
        categoryList.add("纠违处理")
        categoryList.add("标化资料")
        categoryList.add("标化检查")
        categoryList.add("隐患排查")
        categoryList.add("培训学习")

        val cateAdapter = CategoryAdapter(R.layout.item_dia_rectify_manage).apply {
            addData(categoryList)
            setOnItemClickListener { adapter, view, position ->
                val data = adapter.data[position] as String
                this@DFRectManage.selectCategory = data
                filterListener?.onFilter(data)
            }
        }
        recy_agency_cateory.apply {
            adapter = cateAdapter
            layoutManager = object : GridLayoutManager(activity, 3) {
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            addItemDecoration(SpacesItemDecoration(0, 10, 5, 30, resources.getColor(R.color.color0092dfblue)))
        }
        /**
         * 标签
         */

        tagList.add("待办任务")
        tagList.add("任务跟踪")
        val tagAdapter = CategoryAdapter(R.layout.item_dia_rectify_manage).apply {
            addData(tagList)
            setOnItemClickListener { adapter, view, position ->
                val data = adapter.data[position] as String
                this@DFRectManage.selectTag = data
                filterListener?.onFilter(data)
            }
        }
        recy_agency_tags.apply {
            adapter = tagAdapter
            layoutManager = object : GridLayoutManager(activity, 3) {
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            addItemDecoration(SpacesItemDecoration(0, 5, 5, 50, resources.getColor(R.color.color0092dfblue)))
        }
        // 开始时间
        tv_start_time.setOnClickListener {
            val datePickerDialogFragment = DatePickerDiaFragment.newInstance()
            datePickerDialogFragment.show(childFragmentManager, "DatePicker")
            datePickerDialogFragment.setOnDateTapedListener { date ->
                tv_start.gone(false)
                tv_and.gone(false)
                tv_start.text = sdf("yy.MM.dd").format(date)
            }
        }
        // 结束时间
        tv_end_time.setOnClickListener {
            val datePickerDialogFragment = DatePickerDiaFragment.newInstance()
            datePickerDialogFragment.show(childFragmentManager, "DatePicker")
            datePickerDialogFragment.setOnDateTapedListener { date ->
                tv_end.gone(false)
                tv_end.text = sdf("yy.MM.dd").format(date)
            }
        }
        // 搜索跨过
        et_earch.watchWithClear(iv_clear)
        // dismiss once touch
        view?.apply {
            setOnTouchListener { v, event ->
                var starX = 0
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> starX = event.x.toInt()
                    MotionEvent.ACTION_UP,
                    MotionEvent.ACTION_CANCEL -> {
                        val endX = event.x.toInt()
                        if (endX - starX > 10) dismiss()
                    }
                }
                return@setOnTouchListener v.performClick()
            }
        }
        activity?.setFinishOnTouchOutside(true)
        dialog.window.decorView.setOnTouchListener { v, event ->
            dismiss()
            return@setOnTouchListener false
        }
        // 重置
        tv_reset.setOnClickListener {
            et_earch.setText("")
            tv_start.apply {
                text = ""
                gone(true)
            }
            tv_end.apply {
                text = ""
                gone(true)
            }
            tv_and.gone(true)
        }
        // 搜索
        tv_search.setOnClickListener {
            val selectKeyWord = mutableListOf(
                    et_earch.string(),
                    selectCategory,
                    selectTag
            )
            filterListener?.onFilter(selectKeyWord.append(","))
            dismiss()
        }
    }

    /**
     * 初始化布局
     */
    private fun initLayout() {
        val screenWidth = resources.displayMetrics.widthPixels
        val screenHeight = resources.displayMetrics.heightPixels

        val lp = dialog.window.attributes
        lp.width = (screenWidth * 0.75).toInt()
        lp.height = screenHeight
        lp.gravity = Gravity.RIGHT
        dialog.window.attributes = lp
    }


    override fun onDismiss(dialog: DialogInterface?) {
        super.onDismiss(dialog)
        activity?.apply {
            windowOpacity(1.0F)
            KeyboardUtils.hideSoftInput(this)
        }
    }

    fun addFilterListener(listener: (String) -> Unit) {
        filterListener = object : FilterListener {
            override fun onFilter(keyword: String) {
                listener(keyword)
            }
        }
    }

    inner class CategoryAdapter(@LayoutRes layoutRes: Int) : BaseQuickAdapter<String, BaseViewHolder>(layoutRes) {
        override fun convert(helper: BaseViewHolder?, item: String?) {
            if (item == null) return
            helper?.apply {
                setText(R.id.tv_category_name, item)
            }
        }
    }

    /**
     * @warning keyword 是以 , 连接的字符串，分别表示
     *                  搜索关键字
     *                  分类关键字
     *                  标签关键字
     *                  3 个 值
     */
    interface FilterListener {
        fun onFilter(keyword: String)
    }

}